题面传送门:P15853 [蓝桥杯第二届国际赛] 特殊日期
题目大意
枚举日期,寻找有至少三位连续数字日期的个数。
思路讲解
本题分为两大块,一是日期的枚举,二是是否连续的判断。
-
日期枚举
我们可以定义一个函数,从而使得循环变量 的变化符合生活中日期的变化。
-
连续性判断
可对八位日期进行拆位,计算连续数字个数,达到 就是特殊日期。
代码实现
循环变量自增函数
int nxt(int x){ year=x/10000;month=x%10000/100;day=x%100; if(month==1||month==3||month==5||month==7||month==8||month==10){ if(day!=31) return x+1; }else if(month==12){ if(day!=31) return x+1; return (year+1)*10000+101; }else if(month==2){ if((year%4==0&&year%100!=0)||year%400==0){ if(day!=29) return x+1; }else{ if(day!=28) return x+1; } }else{ if(day!=30) return x+1; } return year*10000+(month+1)*100+1;}对非每月边界的日期直接返回原日期 ,对边界日期则对月 ,日归零,组成新的日期返回。
连续性检查函数
bool check(int x){ pre=x%10; x/=10; cnt=1; while(x!=0){ if(x%10==pre){ cnt++; if(cnt==3) return 1; }else{ cnt=1; } pre=x%10; x/=10; } return 0;}利用拆位方法,与上一个数进行对比从而判断连续性。
主函数枚举 + 函数调用
int main(){ cin>>st>>ed; for(int i=st;i<=ed;i=nxt(i)){ if(check(i)) ans++; } cout<<ans; return 0;}完整代码
#include<bits/stdc++.h>using namespace std;int st,ed,year,month,day,ans,pre,cnt;int nxt(int x){ year=x/10000;month=x%10000/100;day=x%100; if(month==1||month==3||month==5||month==7||month==8||month==10){ if(day!=31) return x+1; }else if(month==12){ if(day!=31) return x+1; return (year+1)*10000+101; }else if(month==2){ if((year%4==0&&year%100!=0)||year%400==0){ if(day!=29) return x+1; }else{ if(day!=28) return x+1; } }else{ if(day!=30) return x+1; } return year*10000+(month+1)*100+1;}bool check(int x){ pre=x%10; x/=10; cnt=1; while(x!=0){ if(x%10==pre){ cnt++; if(cnt==3) return 1; }else{ cnt=1; } pre=x%10; x/=10; } return 0;}int main(){ cin>>st>>ed; for(int i=st;i<=ed;i=nxt(i)){ if(check(i)) ans++; } cout<<ans; return 0;}













